$(document).ready(function () {

  // 初始化：只隐藏外层直接子元素的 section
  $(".details-app-show-content > section").hide().eq(0).show();

  // 点击 tab
  $(".details-app-tabs-list li").on("click", function () {
    let index = $(this).index();

    // 切换选中状态
    $(this).addClass("active").siblings().removeClass("active");

    // 只切换外层 section，不影响子内容
    $(".details-app-show-content > section")
      .hide()
      .eq(index)
      .show();
  });


  const $diamondShapeElement = $('.dm-info-expand-content');

  const htmlContent = DropdownOptions.DiamondShapeSelectOptions.map(option => `
    <div class="dm-shape-content-item">
        <img src="${option.img}" alt="${option.value}">
        <p>${option.value}</p>
    </div>
`).join('');
  $diamondShapeElement.find('.dm-shape-content').empty().append(htmlContent);

  // 钻石形状选中事件
  $diamondShapeElement
    .find('.dm-shape-content')
    .off('click', '.dm-shape-content-item')
    .on('click', '.dm-shape-content-item', function () {
      const $item = $(this);
      const $img = $item.find('img');
      const selectedValue = $item.find('p').text().trim();
      const $selectedCategoryElement = $('.selected-category-info');

      if ($img.hasClass('selected')) {
        // 已经选中 → 取消选中
        $item.removeClass('selected');
        $img.removeClass('selected');
        // 移除 shape 这一项
        $selectedCategoryElement.find('.selected-data-item[data-target="shape"]').remove();

      } else {
        const _html = `
    <div class="selected-data-item" data-target="shape" data-id="${selectedValue}">
      <span>${selectedValue}</span>
      <svg class="clear-shape-btn" width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
        <path d="M3.75772 2.62436L3.79438 2.65802L8.32438 7.18836L12.6877 2.82502C12.8095 2.70204 12.9744 2.63125 13.1474 2.62762C13.3204 2.62399 13.4881 2.6878 13.615 2.80555C13.7418 2.92331 13.8179 3.08578 13.8271 3.25862C13.8363 3.43145 13.778 3.6011 13.6644 3.73169L9.26705 8.13102L13.6307 12.4944C13.7538 12.6161 13.8247 12.7809 13.8285 12.954C13.8322 13.1271 13.7685 13.2949 13.6507 13.4218C13.533 13.5487 13.3705 13.6249 13.1976 13.6341C13.0247 13.6434 12.855 13.585 12.7244 13.4714L8.32438 9.07402L3.79438 13.6047C3.67241 13.7267 3.50789 13.7967 3.3354 13.7999C3.16292 13.8031 2.99589 13.7394 2.86944 13.622C2.74298 13.5047 2.66694 13.3429 2.65729 13.1706C2.64765 12.9984 2.70515 12.8291 2.81772 12.6984L7.38172 8.13102L2.85172 3.60102C2.73057 3.4789 2.66132 3.31468 2.65843 3.14268C2.65555 2.97069 2.71926 2.80423 2.83625 2.67812C2.95324 2.55201 3.11445 2.476 3.28617 2.46598C3.4579 2.45596 3.62685 2.5127 3.75772 2.62436Z" fill="#3C3C3C"/>
      </svg>
    </div>
  `;

        // 单选：清空 shape 选中，再设置当前
        $diamondShapeElement.find('.dm-shape-content-item').removeClass('selected').find('img').removeClass('selected');
        $item.addClass('selected');
        $img.addClass('selected');

        // 替换/新增 shape 项
        const $exist = $selectedCategoryElement.find('.selected-data-item[data-target="shape"]');
        if ($exist.length) {
          $exist.replaceWith(_html);
        } else {
          $selectedCategoryElement.prepend(_html);
        }


        // 绑定 shape 清除按钮事件
        $selectedCategoryElement.off('click', '.clear-shape-btn').on('click', '.clear-shape-btn', function () {
          // 移除 shape 这一项
          $selectedCategoryElement.find('.selected-data-item[data-target="shape"]').remove();
          // 取消选中状态
          $diamondShapeElement.find('.dm-shape-content-item').removeClass('selected').find('img').removeClass('selected');
        });

      }
      allProductsQueryInfo.shape = selectedValue
      getAllProducts()

    });



  /**
 * 通用展开收起切换
 * @param {string} containerSelector 外层容器
 * @param {string} titleSelector 标题点击区域
 * @param {string} contentSelector 内容区域
 */
  function bindToggleExpand (containerSelector, titleSelector, contentSelector) {
    const $container = $(containerSelector);

    function toggleExpand () {
      const $svg = $container.find(`${titleSelector} svg`);
      const $content = $(contentSelector);
      const isVisible = $content.is(':visible');

      // 切换箭头方向
      $svg.css('transform', isVisible ? 'rotate(0deg)' : 'rotate(180deg)');

      // 切换内容显示
      if (isVisible) {
        $content.slideUp();
      } else {
        $content.slideDown();
      }
    }

    // 事件绑定
    $container.on('click', titleSelector, toggleExpand);
  }

  // 调用：钻石形状模块
  bindToggleExpand(
    '.dm-info-expand-content',
    '.dm-info-expand-content-title',
    '.dm-shape-content'
  );

  // 调用：钻石大小模块
  bindToggleExpand(
    '.dm-size-expand-content',
    '.dm-size-expand-content-title',
    '.dm-size-content'
  );

  // 调用：钻石尺寸模块
  bindToggleExpand(
    '.dm-weight-expand-content',
    '.dm-weight-expand-content-title',
    '.dm-weight-content'
  );

  // 调用：钻石颜色模块
  bindToggleExpand(
    '.dm-color-expand-content',
    '.dm-color-expand-content-title',
    '.dm-color-content'
  );



  /**
   * 创建一个范围滑块控件（range slider），支持通过拖拽两个滑块或输入框设置最小值和最大值。
   *
   * @param {Object} options - 配置选项对象
   * @param {HTMLElement} options.slider - 滑块容器元素
   * @param {HTMLElement} options.range - 表示当前选中范围的元素
   * @param {HTMLElement} options.thumbMin - 最小值滑块元素
   * @param {HTMLElement} options.thumbMax - 最大值滑块元素
   * @param {HTMLInputElement} [options.minInput] - 可选，用于显示/编辑最小值的输入框
   * @param {HTMLInputElement} [options.maxInput] - 可选，用于显示/编辑最大值的输入框
   * @param {number} options.min - 允许选择的最小数值
   * @param {number} options.max - 允许选择的最大数值
   * @param {number} options.initialMin - 初始最小值
   * @param {number} options.initialMax - 初始最大值
   * @param {Function} [options.onChange] - 当用户完成操作并确认更改时触发的回调函数，
   *                                        接收参数为包含两个字符串形式数值的数组：[minValue, maxValue]
   * @returns {{
   *   getValues: Function,
   *   setValues: Function
   * }} 返回一个对象，提供获取和设置当前值的方法
   */
  function createRangeSlider ({
    slider,
    range,
    thumbMin,
    thumbMax,
    minInput,
    maxInput,
    min,
    max,
    initialMin,
    initialMax,
    onChange // 回调函数
  }) {
    let currentMin = initialMin;
    let currentMax = initialMax;
    const minGap = 0.01; // 设置最小间隔以避免两个滑块重叠

    /**
     * 将给定值转换为相对于整个滑轨长度的百分比位置
     * @param {number} value - 要转换的数值
     * @returns {number} 百分比值（0-100）
     */
    function valueToPercent (value) {
      return ((value - min) / (max - min)) * 100;
    }

    /**
     * 更新界面显示，并根据需要触发onChange回调
     * @param {boolean} triggerChange - 是否应触发onChange回调
     */
    function updateUI (triggerChange = false) {
      const minPercent = valueToPercent(currentMin);
      const maxPercent = valueToPercent(currentMax);

      thumbMin.style.left = minPercent + "%";
      thumbMax.style.left = maxPercent + "%";
      range.style.left = minPercent + "%";
      range.style.width = (maxPercent - minPercent) + "%";

      if (minInput) minInput.value = currentMin.toFixed(2);
      if (maxInput) maxInput.value = currentMax.toFixed(2);

      // 触发回调（仅在需要时）
      if (triggerChange && typeof onChange === "function") {
        onChange([minInput.value, maxInput.value]);
      }
    }

    /**
     * 处理滑块被鼠标按下后的拖动逻辑
     * @param {HTMLElement} thumb - 被拖动的滑块元素
     * @param {boolean} isMin - 标识是否是最小值滑块
     */
    function dragThumb (thumb, isMin) {
      let rect = slider.getBoundingClientRect();
      thumb.style.zIndex = 5;

      function onMove (e) {
        let x = e.clientX - rect.left;
        let percent = (x / rect.width) * 100;
        let value = min + (percent / 100) * (max - min);

        if (isMin) {
          if (value > currentMax - minGap) value = currentMax - minGap;
          if (value < min) value = min;
          currentMin = value;
        } else {
          if (value < currentMin + minGap) value = currentMin + minGap;
          if (value > max) value = max;
          currentMax = value;
        }
        updateUI(); // 拖动过程不触发 onChange
      }

      function onUp () {
        thumb.style.zIndex = 5;
        const otherThumb = isMin ? thumbMax : thumbMin;
        otherThumb.style.zIndex = 1;
        document.removeEventListener("mousemove", onMove);
        document.removeEventListener("mouseup", onUp);

        updateUI(true); // 松手后触发 onChange
      }

      document.addEventListener("mousemove", onMove);
      document.addEventListener("mouseup", onUp);
    }

    // 绑定滑块的鼠标按下事件处理程序
    thumbMin.addEventListener("mousedown", () => dragThumb(thumbMin, true));
    thumbMax.addEventListener("mousedown", () => dragThumb(thumbMax, false));

    // 如果提供了输入框，则绑定其失焦事件来更新对应值
    if (minInput) {
      minInput.addEventListener("blur", () => {
        let v = parseFloat(minInput.value);
        if (isNaN(v)) return;
        if (v < min) v = min;
        if (v >= currentMax) v = currentMax - minGap;
        currentMin = v;
        updateUI(true);
      });
    }

    if (maxInput) {
      maxInput.addEventListener("blur", () => {
        let v = parseFloat(maxInput.value);
        if (isNaN(v)) return;
        if (v > max) v = max;
        if (v <= currentMin) v = currentMin + minGap;
        currentMax = v;
        updateUI(true);
      });
    }

    // 初始化界面状态
    updateUI();



    return {
      /**
       * 获取当前选定的最小值与最大值
       * @returns {[number, number]} 包含当前最小值和最大值的数组
       */
      getValues: () => [currentMin, currentMax],

      /**
       * 设置新的最小值和最大值
       * @param {number} minVal - 新的最小值
       * @param {number} maxVal - 新的最大值
       */
      setValues: (minVal, maxVal) => {
        currentMin = Math.max(min, Math.min(minVal, max));
        currentMax = Math.max(min, Math.min(maxVal, max));
        updateUI(true);
      }
    };
  }

  const $selectedCategoryElement = $('.selected-category-info');



  // 钻石大小 slider
  createRangeSlider({
    slider: document.getElementById("dm-size-slider"),
    range: document.getElementById("dm-size-slider-range"),
    thumbMin: document.getElementById("dm-size-thumb-min"),
    thumbMax: document.getElementById("dm-size-thumb-max"),
    minInput: document.getElementById("dm-size-min-input"),
    maxInput: document.getElementById("dm-size-max-input"),
    min: 4.0,
    max: 20.0,
    initialMin: 4.0,
    initialMax: 20.0,
    onChange: ([min, max]) => {
      const _html = `<div class="selected-data-item" data-target="dmSize" >
          <span>Size ${min} - ${max}</span>
          <svg class="clear-size-btn" width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
            <g clip-path="url(#clip0_52_3741)">
              <path
                d="M3.75772 2.62436L3.79438 2.65802L8.32438 7.18836L12.6877 2.82502C12.8095 2.70204 12.9744 2.63125 13.1474 2.62762C13.3204 2.62399 13.4881 2.6878 13.615 2.80555C13.7418 2.92331 13.8179 3.08578 13.8271 3.25862C13.8363 3.43145 13.778 3.6011 13.6644 3.73169L13.631 3.76836L9.26705 8.13102L13.6307 12.4944C13.7538 12.6161 13.8247 12.7809 13.8285 12.954C13.8322 13.1271 13.7685 13.2949 13.6507 13.4218C13.533 13.5487 13.3705 13.6249 13.1976 13.6341C13.0247 13.6434 12.855 13.585 12.7244 13.4714L12.6877 13.4374L8.32438 9.07402L3.79438 13.6047C3.67241 13.7267 3.50789 13.7967 3.3354 13.7999C3.16292 13.8031 2.99589 13.7394 2.86944 13.622C2.74298 13.5047 2.66694 13.3429 2.65729 13.1706C2.64765 12.9984 2.70515 12.8291 2.81772 12.6984L2.85138 12.6617L7.38172 8.13102L2.85172 3.60102C2.73057 3.4789 2.66132 3.31468 2.65843 3.14268C2.65555 2.97069 2.71926 2.80423 2.83625 2.67812C2.95324 2.55201 3.11445 2.476 3.28617 2.46598C3.4579 2.45596 3.62685 2.5127 3.75772 2.62436Z"
                fill="#3C3C3C" />
            </g>
          </svg>
        </div>
        `
      const $item = $selectedCategoryElement.find('.selected-data-item[data-target="dmSize"]');
      if ($item.length) {
        $item.replaceWith(_html); // 已有 → 替换
      } else {
        $selectedCategoryElement.prepend(_html); // 没有 → 追加
        // 绑定 size 清除按钮事件
        $selectedCategoryElement.off('click', '.clear-size-btn').on('click', '.clear-size-btn', function () {
          $(this).closest('.selected-data-item[data-target="dmSize"]').remove();
        });

      }

      allProductsQueryInfo.size = [min, max]
      getAllProducts()
    }
  });

  // 钻石体积 slider
  createRangeSlider({
    slider: document.getElementById("dm-weight-slider"),
    range: document.getElementById("dm-weight-slider-range"),
    thumbMin: document.getElementById("dm-weight-thumb-min"),
    thumbMax: document.getElementById("dm-weight-thumb-max"),
    minInput: document.getElementById("dm-weight-min-input"),
    maxInput: document.getElementById("dm-weight-max-input"),
    min: 1.36,
    max: 56.77,
    initialMin: 1.36,
    initialMax: 56.77,
    onChange: ([min, max]) => {
      const _html = `<div class="selected-data-item" data-target="dmWeight" >
          <span>Weight ${min}-${max}</span>
          <svg class="clear-weight-btn" width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
            <g clip-path="url(#clip0_52_3741)">
              <path
                d="M3.75772 2.62436L3.79438 2.65802L8.32438 7.18836L12.6877 2.82502C12.8095 2.70204 12.9744 2.63125 13.1474 2.62762C13.3204 2.62399 13.4881 2.6878 13.615 2.80555C13.7418 2.92331 13.8179 3.08578 13.8271 3.25862C13.8363 3.43145 13.778 3.6011 13.6644 3.73169L13.631 3.76836L9.26705 8.13102L13.6307 12.4944C13.7538 12.6161 13.8247 12.7809 13.8285 12.954C13.8322 13.1271 13.7685 13.2949 13.6507 13.4218C13.533 13.5487 13.3705 13.6249 13.1976 13.6341C13.0247 13.6434 12.855 13.585 12.7244 13.4714L12.6877 13.4374L8.32438 9.07402L3.79438 13.6047C3.67241 13.7267 3.50789 13.7967 3.3354 13.7999C3.16292 13.8031 2.99589 13.7394 2.86944 13.622C2.74298 13.5047 2.66694 13.3429 2.65729 13.1706C2.64765 12.9984 2.70515 12.8291 2.81772 12.6984L2.85138 12.6617L7.38172 8.13102L2.85172 3.60102C2.73057 3.4789 2.66132 3.31468 2.65843 3.14268C2.65555 2.97069 2.71926 2.80423 2.83625 2.67812C2.95324 2.55201 3.11445 2.476 3.28617 2.46598C3.4579 2.45596 3.62685 2.5127 3.75772 2.62436Z"
                fill="#3C3C3C" />
            </g>
          </svg>
        </div>
        `
      const $item = $selectedCategoryElement.find('.selected-data-item[data-target="dmWeight"]');
      if ($item.length) {
        $item.replaceWith(_html); // 已有 → 替换
      } else {
        $selectedCategoryElement.prepend(_html); // 没有 → 追加
        $selectedCategoryElement.off('click', '.clear-weight-btn').on('click', '.clear-weight-btn', function () {
          $(this).closest('.selected-data-item[data-target="dmWeight"]').remove();
        });
      }

      allProductsQueryInfo.weight = [min, max]
      getAllProducts()

    }
  });


  // 颜色滑块选择
  const $slider = $("#slider");
  const $colorThumb = $slider.find("#color-thumb");
  const labels = $slider.find(".slider-labels span");
  const selectedLetterEl = $("#selected-letter");
  const trackBlocks = $slider.find(".track-block");
  let positions = []; // 每个块的中心像素位置
  let currentIndex = 0;

  // 🟢 封装计算函数
  function computePositions () {
    positions = [];
    const sliderRect = $slider[0].getBoundingClientRect();
    trackBlocks.each(function () {
      const blockRect = this.getBoundingClientRect();
      const center = (blockRect.left - sliderRect.left) + (blockRect.width / 2);
      positions.push(center);
    });
  }

  // 🟢 更新滑块
  function updateThumb (index) {
    if (index < 0) index = 0;
    if (index >= positions.length) index = positions.length - 1;

    currentIndex = index;
    const sliderRect = $slider[0].getBoundingClientRect();
    const percent = (positions[index] / sliderRect.width) * 100;

    $colorThumb.css("left", percent + "%");

    const colorValue = labels.eq(index).text();
    const _html = `
    <div class="selected-data-item" data-target="dmColor" data-color-value="${colorValue}">
      <span>Color ${colorValue}</span>
      <svg class="clear-color-btn" width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
        <path
          d="M3.75772 2.62436L3.79438 2.65802L8.32438 7.18836L12.6877 2.82502C12.8095 2.70204 12.9744 2.63125 13.1474 2.62762C13.3204 2.62399 13.4881 2.6878 13.615 2.80555C13.7418 2.92331 13.8179 3.08578 13.8271 3.25862C13.8363 3.43145 13.778 3.6011 13.6644 3.73169L9.26705 8.13102L13.6307 12.4944C13.7538 12.6161 13.8247 12.7809 13.8285 12.954C13.8322 13.1271 13.7685 13.2949 13.6507 13.4218C13.533 13.5487 13.3705 13.6249 13.1976 13.6341C13.0247 13.6434 12.855 13.585 12.7244 13.4714L8.32438 9.07402L3.79438 13.6047C3.67241 13.7267 3.50789 13.7967 3.3354 13.7999C3.16292 13.8031 2.99589 13.7394 2.86944 13.622C2.74298 13.5047 2.66694 13.3429 2.65729 13.1706C2.64765 12.9984 2.70515 12.8291 2.81772 12.6984L7.38172 8.13102L2.85172 3.60102C2.73057 3.4789 2.66132 3.31468 2.65843 3.14268C2.65555 2.97069 2.71926 2.80423 2.83625 2.67812C2.95324 2.55201 3.11445 2.476 3.28617 2.46598C3.4579 2.45596 3.62685 2.5127 3.75772 2.62436Z"
          fill="#3C3C3C"
        />
      </svg>
    </div>
  `;

    const $item = $selectedCategoryElement.find('.selected-data-item[data-target="dmColor"]');
    if ($item.length) {
      $item.replaceWith(_html);
    } else {
      $selectedCategoryElement.prepend(_html);
      // 绑定删除事件
      $selectedCategoryElement.off('click', '.clear-color-btn').on('click', '.clear-color-btn', function () {
        $(this).closest('.selected-data-item[data-target="dmColor"]').remove();
      });
    }

    // 更新查询条件
    allProductsQueryInfo.color = colorValue;
    getAllProducts();
  }

  // 🟢 点击滑轨跳转
  $slider.on('click', function (e) {
    // 忽略点击 thumb 自身
    if (e.target === $colorThumb[0]) return;

    computePositions(); // 点击前重新计算，防止尺寸变化出错

    const sliderRect = $slider[0].getBoundingClientRect();
    let x = e.clientX - sliderRect.left;
    x = Math.max(0, Math.min(x, sliderRect.width));

    let closestIndex = 0;
    let minDist = Infinity;
    positions.forEach((pos, i) => {
      const dist = Math.abs(pos - x);
      if (dist < minDist) {
        minDist = dist;
        closestIndex = i;
      }
    });

    updateThumb(closestIndex);
  });


  // 初始计算
  computePositions();


  // 默认初始选择颜色
  function resetSelectedColor () {
    // 重新计算块中心位置，保证响应式
    positions.length = 0;
    const $slider = $("#slider"); // jQuery 包装 slider
    trackBlocks.each(function (block) {
      const $block = $(this);
      const sliderLeft = $slider.offset().left;
      const blockLeft = $block.offset().left;
      const blockWidth = $block.outerWidth();
      const centerPx = blockLeft - sliderLeft + blockWidth / 2;
      positions.push(centerPx); // 保存像素位置
    });
    updateThumb(currentIndex);
  }

  // 初始化清空按钮
  let $clearAllBtn = $selectedCategoryElement.find('.selected-close');

  if ($selectedCategoryElement.find('.selected-data-item').length > 0) {
    $clearAllBtn = $(`
      <div class="selected-close">
          <span>Reset All</span>
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
            <g clip-path="url(#clip0_249_20462)">
              <path
                d="M3.75772 2.62436L3.79438 2.65802L8.32438 7.18836L12.6877 2.82502C12.8095 2.70204 12.9744 2.63125 13.1474 2.62762C13.3204 2.62399 13.4881 2.6878 13.615 2.80555C13.7418 2.92331 13.8179 3.08578 13.8271 3.25862C13.8363 3.43145 13.778 3.6011 13.6644 3.73169L13.631 3.76836L9.26705 8.13102L13.6307 12.4944C13.7538 12.6161 13.8247 12.7809 13.8285 12.954C13.8322 13.1271 13.7685 13.2949 13.6507 13.4218C13.533 13.5487 13.3705 13.6249 13.1976 13.6341C13.0247 13.6434 12.855 13.585 12.7244 13.4714L12.6877 13.4374L8.32438 9.07402L3.79438 13.6047C3.67241 13.7267 3.50789 13.7967 3.3354 13.7999C3.16292 13.8031 2.99589 13.7394 2.86944 13.622C2.74298 13.5047 2.66694 13.3429 2.65729 13.1706C2.64765 12.9984 2.70515 12.8291 2.81772 12.6984L2.85138 12.6617L7.38172 8.13102L2.85172 3.60102C2.73057 3.4789 2.66132 3.31468 2.65843 3.14268C2.65555 2.97069 2.71926 2.80423 2.83625 2.67812C2.95324 2.55201 3.11445 2.476 3.28617 2.46598C3.4579 2.45596 3.62685 2.5127 3.75772 2.62436Z"
                fill="#CCB591" />
            </g>
          </svg>
        </div>
      `);
    $selectedCategoryElement.append($clearAllBtn);
  }

  const $container = $('.selected-category-info')[0]; // 原生 DOM 节点

  const observer = new MutationObserver((mutationsList) => {
    mutationsList.forEach((mutation) => {
      if (mutation.type === 'childList') {
        // 判断是否新增了 selected-data-item
        const added = Array.from(mutation.addedNodes).some(node =>
          node.nodeType === 1 && $(node).hasClass('selected-data-item')
        );
        if (added) {
          $('.selected-category-info').css('display', 'flex');
          $('.dm-info-expand-content').css('border-top', 'none');
          // 先检查按钮是否存在
          let $clearAllBtn = $selectedCategoryElement.find('.selected-close');
          if ($clearAllBtn.length === 0) {
            $clearAllBtn = $(`
            <div class="selected-close">
              <span>Reset All</span>
              <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                <g clip-path="url(#clip0_249_20462)">
                  <path
                    d="M3.75772 2.62436L3.79438 2.65802L8.32438 7.18836L12.6877 2.82502C12.8095 2.70204 12.9744 2.63125 13.1474 2.62762C13.3204 2.62399 13.4881 2.6878 13.615 2.80555C13.7418 2.92331 13.8179 3.08578 13.8271 3.25862C13.8363 3.43145 13.778 3.6011 13.6644 3.73169L13.631 3.76836L9.26705 8.13102L13.6307 12.4944C13.7538 12.6161 13.8247 12.7809 13.8285 12.954C13.8322 13.1271 13.7685 13.2949 13.6507 13.4218C13.533 13.5487 13.3705 13.6249 13.1976 13.6341C13.0247 13.6434 12.855 13.585 12.7244 13.4714L12.6877 13.4374L8.32438 9.07402L3.79438 13.6047C3.67241 13.7267 3.50789 13.7967 3.3354 13.7999C3.16292 13.8031 2.99589 13.7394 2.86944 13.622C2.74298 13.5047 2.66694 13.3429 2.65729 13.1706C2.64765 12.9984 2.70515 12.8291 2.81772 12.6984L2.85138 12.6617L7.38172 8.13102L2.85172 3.60102C2.73057 3.4789 2.66132 3.31468 2.65843 3.14268C2.65555 2.97069 2.71926 2.80423 2.83625 2.67812C2.95324 2.55201 3.11445 2.476 3.28617 2.46598C3.4579 2.45596 3.62685 2.5127 3.75772 2.62436Z"
                    fill="#CCB591" />
                </g>
              </svg>
            </div>
          `);
            $selectedCategoryElement.append($clearAllBtn);

            // 绑定清空按钮事件
            $clearAllBtn.off('click').on('click', function () {
              $selectedCategoryElement.find('.selected-data-item').remove();
              // 取消选中状态
              $diamondShapeElement.find('.dm-shape-content-item').removeClass('selected').find('img').removeClass('selected');

              // 清空筛选条件
              allProductsQueryInfo = {
                page: 1,
                pageSize: 10,
                shape: null,
                size: null,
                weight: null,
                color: null
              }
              getAllProducts()
            });

          }
        } else {
          // 判断是否删除了 selected-data-item
          const hasItems = $selectedCategoryElement.find('.selected-data-item').length > 0;
          if (!hasItems) {
            // 移除按钮
            $selectedCategoryElement.find('.selected-close').remove();
            $('.selected-category-info').hide();
            $('.dm-info-expand-content').css('border-top', '0.1rem solid #E1E1E1');
          }
        }
      }
    });
  });


  // 配置监听：只监控子节点的增删
  observer.observe($container, { childList: true });

  var allProductsQueryInfo = {
    page: 1,
    pageSize: 10,
    shape: null,
    size: null,
    weight: null,
    color: null
  }




  const $productsContainer = $(".right-show-all-products");
  const $allProducts = $productsContainer.find(".all-products-content");
  const $myCollection = $productsContainer.find(".my-collection-content");

  // 封装切换函数
  function switchTab ($clicked, $show, $hide) {
    $show.show();
    $hide.hide();

    // 先清空，再加高亮
    $(".products-header-info div").removeClass("products-selected");
    $clicked.addClass("products-selected");
  }

  // 默认显示 All Diamonds
  $(".products-header-info .header-info-left").addClass("products-selected");
  $allProducts.show();
  console.log("allProductsQueryInfo", $allProducts);

  $myCollection.hide();

  // 点击 All Diamonds
  $productsContainer.on("click", ".header-info-left", function () {
    switchTab($(this), $allProducts, $myCollection);
  });

  // 点击 Compare
  $productsContainer.on("click", ".header-info-right", function () {
    switchTab($(this), $myCollection, $allProducts);
  });


  // 定义映射关系
  const dropdownMap = {
    '#countryList': DropdownOptions.CountryListSelect || []
  };

  // 渲染函数
  function renderOptions ($ul, options) {
    $ul.empty();
    options.forEach(opt => {
      $ul.append(`<li data-value="${opt.value}">${opt.label}</li>`);
    });
  }

  // 批量渲染
  Object.entries(dropdownMap).forEach(([selector, options]) => {
    renderOptions($(selector), options);
  });

  // 打开/关闭当前下拉（并关闭其它）
  $('.select-dropdown').on('click', function (e) {
    e.stopPropagation();
    $('.select-dropdown').not(this).removeClass('open');
    $(this).toggleClass('open');
  });
  $(document).on('click', () => $('.select-dropdown').removeClass('open'));
  $('.select-dropdown').click(function () {
    var dropdown = $(this);
    var ul = dropdown.children('ul');
    var p = dropdown.find('p');
    var input = dropdown.find('input');
    // 如果为二级下拉
    if (ul.find('ul li').length) {
      var li = ul.find('ul li');
    } else {
      // 一级
      var li = ul.find('li');
    }

    var arrows = dropdown.find('.select-arrows');
    if (ul.css('display') == 'none') {
      ul.slideDown('fast');
      arrows.css('transform', 'rotate(180deg)');
    } else {
      ul.slideUp('fast');
      arrows.css('transform', 'rotate(0)');
    }

    li.click(function () {
      var txt = $(this).text();
      var firstSelect = $(this).parent().prev().text();
      p.html(`${firstSelect} ${txt}`);
      input.val(`${firstSelect} ${txt}`);
      ul.slideUp('fast');
      arrows.css('transform', 'rotate(0)');
    });
    dropdown.mouseleave(function () {
      ul.slideUp('fast');
      arrows.css('transform', 'rotate(0)');
    });
  });
  // 点击其他地方关闭下拉
  $(document).click(function () {
    $('.select-dropdown').removeClass('open');
  });

  // 校验字段
  const validationRules = [
    {
      key: 'consultingName',
      required: true,
      maxLength: 50,
      errorMessage: {
        required: 'Please enter your name',
        maxLength: 'The length cannot exceed 50'
      }
    },
    {
      key: 'companyName',
      required: false,
    },
    {
      key: 'email',
      required: true,
      maxLength: 30,
      regex: regEmail,
      errorMessage: {
        required: 'Please enter your email',
        maxLength: 'The length cannot exceed 30',
        regex: 'Please enter a valid email'
      }
    },
    {
      key: 'country',
      required: true,
      errorMessage: {
        required: 'Please Select your Country'
      }
    },
    {
      key: 'PhoneNumber',
      required: true,
      regex: regPhone,
      errorMessage: {
        required: 'Please enter your Phone',
        regex: 'Please enter a valid phone number'
      }
    },
    {
      key: 'checkbox',
      required: false
    },
    {
      key: 'message',
      required: true,
      maxLength: 200,
      errorMessage: {
        required: 'Please Select your Message',
        maxLength: 'The length cannot exceed 200'
      }
    }
  ];


  // 获取全部的产品数据
  const $productsInfoElement = $('.right-show-all-products')

  // 接口获取全部数据
  function getAllProducts () {

    const params = {
      page: 1,
      page_size: 10,
      total: 16,
      list: [{
        id: 10075,
        img: "../../img/PC/diamond.png",
        title: "CB4512 Monocrystalline Synthetic Diamond",
        desc: "Ideal Cut, DColor, VVS2 Clarity 12715127A",
        is_like: false,
      }, {
        id: 10076,
        img: "../../img/PC/diamond.png",
        title: "CB4512 Monocrystalline Synthetic Diamond",
        desc: "Ideal Cut, DColor, VVS2 Clarity 12715127A",
        is_like: false,
      },
      {
        id: 10077,
        img: "../../img/PC/diamond.png",
        title: "CB4512 Monocrystalline Synthetic Diamond",
        desc: "Ideal Cut, DColor, VVS2 Clarity 12715127A",
        is_like: false,
      },
      {
        id: 10078,
        img: "../../img/PC/app_img.png",
        title: "CB4512 Monocrystalline Synthetic Diamond",
        desc: "Ideal Cut, DColor, VVS2 Clarity 12715127A",
        is_like: false,
      },
      {
        id: 10079,
        img: "../../img/PC/categories_img.png",
        title: "CB4512 Monocrystalline Synthetic Diamond",
        desc: "Ideal Cut, DColor, VVS2 Clarity 12715127A",
        is_like: false,
      },
      {
        id: 10080,
        img: "../../img/PC/diamond.png",
        title: "CB4512 Monocrystalline Synthetic Diamond",
        desc: "Ideal Cut, DColor, VVS2 Clarity 12715127A",
        is_like: false,
      },
      {
        id: 10081,
        img: "../../img/PC/diamond.png",
        title: "CB4512 Monocrystalline Synthetic Diamond",
        desc: "Ideal Cut, DColor, VVS2 Clarity 12715127A",
        is_like: false,
      },
      {
        id: 10076,
        img: "../../img/PC/diamond.png",
        title: "CB4512 Monocrystalline Synthetic Diamond",
        desc: "Ideal Cut, DColor, VVS2 Clarity 12715127A",
        is_like: false,
      },
      {
        id: 10076,
        img: "../../img/PC/diamond.png",
        title: "CB4512 Monocrystalline Synthetic Diamond",
        desc: "Ideal Cut, DColor, VVS2 Clarity 12715127A",
        is_like: false,
      },
      {
        id: 10076,
        img: "../../img/PC/diamond.png",
        title: "CB4512 Monocrystalline Synthetic Diamond",
        desc: "Ideal Cut, DColor, VVS2 Clarity 12715127A",
        is_like: false,
      },
      {
        id: 10076,
        img: "../../img/PC/diamond.png",
        title: "CB4512 Monocrystalline Synthetic Diamond",
        desc: "Ideal Cut, DColor, VVS2 Clarity 12715127A",
        is_like: false,
      },
      {
        id: 10076,
        img: "../../img/PC/diamond.png",
        title: "CB4512 Monocrystalline Synthetic Diamond",
        desc: "Ideal Cut, DColor, VVS2 Clarity 12715127A",
        is_like: false,
      },
      {
        id: 10076,
        img: "../../img/PC/diamond.png",
        title: "CB4512 Monocrystalline Synthetic Diamond",
        desc: "Ideal Cut, DColor, VVS2 Clarity 12715127A",
        is_like: false,
      },
      ]
    }

    // 清空重新渲染
    $productsInfoElement.find(".all-products-body").empty();
    $productsInfoElement.find('.header-info-left span').text(`(${params.total})`)

    // 咨询更多
    const _needHelpMoreHtml = `<aside class="need-help-more">
          <h4 class="need-title">Need help finding the perfect diamond?</h4>
          <button class="need-help-btn">Try Our Diamond Finder</button>
        </aside>`
    params.list.forEach((item, index) => {

      const _products_html = `
         <div class="all-products-item" data-products='${JSON.stringify(item)}'>
          <div class="products-img">
            <img src="${item.img}" alt="">
            <div data-products='${JSON.stringify(item)}' class="products-my-lick ${item.is_like ? 'active' : ''}">
              <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path fill="currentColor"
                  d="M11.4385 1.13672C13.5689 1.13672 15.3758 3.04749 15.376 5.4873C15.376 6.742 14.8914 7.67682 14.3848 8.49316L14.168 8.83594C13.3693 10.081 11.9481 11.5108 10.6738 12.665C9.40786 13.8118 8.32832 14.6502 8.25 14.709L8.24023 14.7158C8.16042 14.7788 8.0718 14.8066 7.98242 14.8066C7.89319 14.8066 7.80528 14.7787 7.72559 14.7158L7.71582 14.709L6.94727 14.0957C6.50866 13.7361 5.92138 13.2406 5.28809 12.668C4.0129 11.515 2.59248 10.0861 1.79883 8.83789L1.79785 8.83594C1.22247 7.9369 0.589844 6.92102 0.589844 5.4873C0.590048 3.04767 2.3961 1.137 4.52637 1.13672C5.71367 1.13672 6.8385 1.73461 7.58008 2.74219L7.98047 3.28613L8.38379 2.74414C9.13578 1.7334 10.2528 1.13684 11.4385 1.13672Z" />
              </svg>
            </div>
          </div>
          <div class="products-title">
            <p>${item.title}</p>
          </div>
          <div class="products-desc">
            <p>${item.desc}</p>
          </div>
          <div class="products-btn">
            <button type="button" class="addBag">
              Add to bag
            </button>
            <button type="button" class="inquiry">
              Inquiry
            </button>
          </div>
        </div>
    `
      $productsInfoElement.find('.all-products-body').append(_products_html)

      RenderPagination(params.page, params.total, 5, $productsInfoElement.find('.all-products-body'), function (targetPage) {
        console.log(targetPage);
      })

      if (getIsMobile()) {
        // 判断是否到了第4行（即8个元素后）
        if ((index + 1) % 8 == 0) {
          $productsInfoElement.find('.all-products-body').append(_needHelpMoreHtml);
        }
      } else {
        // 判断是否到了第4行（即12个元素后）
        if ((index + 1) % 12 == 0) {
          $productsInfoElement.find('.all-products-body').append(_needHelpMoreHtml);
        }
      }

    })

    // 打开弹框
    $productsInfoElement.off('click', '.need-help-btn').on('click', '.need-help-btn', function () {
      $('.contact-dialog').fadeIn();
    });

    // 联系客服提交按钮
    $('.dm-dialog-btn').click(function () {
      const formValues = FormValidator.validateForm(validationRules, $('#refDialogWrite'));
      if (!formValues.valid) return;
      console.log('提交表单', formValues.formParam);
      $('.contact-dialog').fadeOut();
      DMshowToast('Success!');
    });

    // 关闭弹框
    $('.dm-header-close-btn').on('click', function () {
      $('.contact-dialog').fadeOut();
    })

    // 点击收藏
    $productsInfoElement.find('.products-my-lick').on('click', function () {
      const productData = $(this).data('products')

      // 判断是否已收藏
      if ($(this).hasClass('active')) {
        $(this).removeClass('active')
        LocalStore.removeItem('myCollectionList', productData.id)

      } else {
        $(this).toggleClass('active')
        LocalStore.update(
          'myCollectionList',
          function (oldValue) {
            oldValue = Array.isArray(oldValue) ? oldValue : [] // 确保旧值是数组
            oldValue.push(productData) // 追加新数据
            return oldValue
          },
          'id'
        )
        DMshowToast('Success!')
      }
      getAllMyCollectionProducts()
    })

    // 点击 Add to bag
    $productsInfoElement.off('click', '.addBag').on('click', '.addBag', function () {
      const $rowBagParams = $(this).closest('.all-products-item').data('products')
      LocalStore.update(
        'storeBagList',
        function (oldValue) {
          oldValue = Array.isArray(oldValue) ? oldValue : [] // 确保旧值是数组
          oldValue.push($rowBagParams) // 追加新数据
          return oldValue
        },
        'id'
      )
      DMshowToast('Success!')

    })

    // 点击Inquiry
    $productsInfoElement.off('click', '.inquiry').on('click', '.inquiry', function () {
      const $rowBagParams = $(this).closest('.all-products-item').data('products')
      window.location.href = `/inquiry-list.html`
    })
  }

  // 获取我喜爱的产品
  function getAllMyCollectionProducts () {
    const $myCollectionContent = $productsInfoElement.find(".my-collection-content");
    const $headerCount = $productsInfoElement.find('.header-info-right span');
    // 清空列表
    $myCollectionContent.empty();
    const collectionList = LocalStore.get("myCollectionList") || [];
    // 更新数量
    $headerCount.text(`(${collectionList.length})`);

    // 返回ALL Products
    const _returnAllProductsHtml = `<div class="return-all-diamond">
          return to all diamonds
        </div>`
    $myCollectionContent.append(_returnAllProductsHtml);
    // 点击返回ALL Products
    $myCollectionContent.off('click', '.return-all-diamond').on('click', '.return-all-diamond', function () {
      switchTab($(".header-info-left"), $allProducts, $myCollection);
    })
    if (!collectionList.length) return;

    // 拼接 HTML 并一次性追加，避免多次操作 DOM
    const html = collectionList.map(item => `
    <div class="my-products-item" data-products='${JSON.stringify(item)}'>
      <div class="products-img">
        <img src="${item.img}" alt="">
        <div data-products='${JSON.stringify(item)}' class="products-my-lick active" >
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path fill="currentColor"
              d="M11.4385 1.13672C13.5689 1.13672 15.3758 3.04749 15.376 5.4873C15.376 6.742 14.8914 7.67682 14.3848 8.49316L14.168 8.83594C13.3693 10.081 11.9481 11.5108 10.6738 12.665C9.40786 13.8118 8.32832 14.6502 8.25 14.709L8.24023 14.7158C8.16042 14.7788 8.0718 14.8066 7.98242 14.8066C7.89319 14.8066 7.80528 14.7787 7.72559 14.7158L7.71582 14.709L6.94727 14.0957C6.50866 13.7361 5.92138 13.2406 5.28809 12.668C4.0129 11.515 2.59248 10.0861 1.79883 8.83789L1.79785 8.83594C1.22247 7.9369 0.589844 6.92102 0.589844 5.4873C0.590048 3.04767 2.3961 1.137 4.52637 1.13672C5.71367 1.13672 6.8385 1.73461 7.58008 2.74219L7.98047 3.28613L8.38379 2.74414C9.13578 1.7334 10.2528 1.13684 11.4385 1.13672Z" />
          </svg>
        </div>
      </div>
      <div class="products-title"><p>${item.title}</p></div>
      <div class="products-desc"><p>${item.desc}</p></div>
      <div class="products-btn">
        <button type="button" class="addBag">Add to bag</button>
        <button type="button" class="inquiry">Inquiry</button>
      </div>
    </div>
  `).join('');

    $myCollectionContent.prepend(html);

    // 取消收藏
    $myCollectionContent.off('click', '.products-my-lick').on('click', '.products-my-lick', function () {
      const productData = $(this).data('products')
      LocalStore.removeItem('myCollectionList', productData.id)
      getAllMyCollectionProducts()
      getAllProducts()
    })

    // 点击 Add to bag
    $myCollectionContent.off('click', '.addBag').on('click', '.addBag', function () {
      const $rowBagParams = $(this).closest('.my-products-item').data('products')
      LocalStore.update(
        'storeBagList',
        function (oldValue) {
          oldValue = Array.isArray(oldValue) ? oldValue : [] // 确保旧值是数组
          oldValue.push($rowBagParams) // 追加新数据
          return oldValue
        },
        'id'
      )
      DMshowToast('Success!')

    })

    // 点击Inquiry
    $myCollectionContent.off('click', '.inquiry').on('click', '.inquiry', function () {
      const $rowBagParams = $(this).closest('.my-products-item').data('products')
      window.location.href = `/inquiry-list.html`
    })
  }

  getAllMyCollectionProducts()

  getAllProducts()

  window.addEventListener('resize', debounce(() => {
    getAllProducts()
    computePositions();
    updateThumb(currentIndex); // 缩放后保持 thumb 对齐
  }, 300))
})